/**
 * 封装Request请求
 */
import axios from 'axios'
import { getToken, logOut } from '../utils/auth'
import setting from '../setting'
import router from '../router/index'

// 超时设定
const timeout = setting.appRequestTimeout

// Token
const key = setting.appTokenKey

// axios实例
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
  // timeout: timeout * 1000
})

request.interceptors.request.use(
  request => {
    if (getToken() !== undefined || getToken() !== null) {
      request.headers['token'] = getToken()
    }
    return request
  },
  error => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => {
    const { data } = response
    if (data.result === 1 || data.result === 2) {
      window.$message.info(`登录超时或该账户在异地登录，请重新登录`)
      logOut()
      router.push({ name: setting.publicIndexPage })
    } else {
      return data
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default request
